package com.bootdo.collector.config;



import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.entity.ContentType;
import org.apache.http.nio.entity.NStringEntity;
import org.apache.http.util.EntityUtils;
import org.elasticsearch.client.Response;
import org.elasticsearch.client.RestClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;


/**
 *
 * 连接ES bean
 * @author liyj
 *
 */
@Configuration
public class ESConfig {

	private Logger logger = LoggerFactory.getLogger(ESConfig.class);

	@Value("${changping.elasticsearch.ips}")
	private String changpingIps;


	/**
	 * 昌平存储用rest client
	 */
	private RestClient consumerClient;


	/**
	 * 程序开始时初始化elasticsearch连接，结束时关闭连接
	 */
	@Bean
	public RestClient restClient() {
		try {
			consumerClient = this.connectionInit(changpingIps);
			getClientInfo(consumerClient);
		} catch (Exception e) {
			this.doShutdownWork();
			System.exit(-1);
		}
		this.doShutdownWork();
		return consumerClient;

	}


	private RestClient connectionInit(String ips) {
		String[] hosts = ips.split(",");
		List<HttpHost> hostList = new ArrayList<>(hosts.length);
		for (String ip : hosts) {
			String[] host = ip.split(":");
			hostList.add(new HttpHost(host[0], Integer.parseInt(host[1])));
		}
		return RestClient.builder(hostList.toArray(new HttpHost[hosts.length])).build();
	}

	private void doShutdownWork() {
		Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
			@Override
			public void run() {

				try {
					consumerClient.close();
				} catch (IOException e) {
					//log.error(e.getMessage(), e);
				}
			}
		}));
	}


	public RestClient getConsumerClient() {
		return consumerClient;
	}

	public void getClientInfo(RestClient client) throws IOException {
		Response resp = client.performRequest("GET", "", Collections.<String, String>emptyMap());
		logger.info("\n{}", EntityUtils.toString(resp.getEntity()));
	}



// 连接例子
//
//	/**	GET*/
//	public String getSensitiveContent(String id) {
//		try {
//			Response resp = dataSource.getConsumerClient().performRequest("GET", "/" + sensitiveIndex + "/doc/" + id);
//			if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
//				JsonNode respJson = JsonUtils.readTree(EntityUtils.toString(resp.getEntity()));
//				return respJson.get("_source").get("content").asText("");
//			}
//		} catch (IOException e) {
//			log.error(e.getMessage(), e);
//		}
//		return "";
//	}
//
//	private JsonNode execQuery(String query, String url) {
//		HttpEntity httpEntity = new NStringEntity(query, ContentType.APPLICATION_JSON);
//		JsonNode respJson = null;
//		int i = 0;
//		// 考虑到国内外网络状况，当请求失败时重复尝试三次
//		while (respJson == null && i++ < 3) {
//			try {
//				Response response = esDataSource.getFetchClient().performRequest("POST", url,
//						Collections.<String, String>emptyMap(), httpEntity);
//				String respStr = EntityUtils.toString(response.getEntity());
//				respJson = JsonUtils.readTree(respStr);
//			} catch (IOException e) {
//				log.error(e.getMessage(), e);
//			}
//		}
//		return respJson;
//	}
//
//	private static final String SCORLL_QUERY = "{\"scroll\": \"5m\",\"scroll_id\":\"%s\"}";
//	/** 使用游标获取接下来的数据 */
//	public Map<String, Object> getNextData(String scrollId) {
//		String query = String.format(SCORLL_QUERY, scrollId);
//		Map<String, Object> data = new HashMap<>();
//		JsonNode respJson = this.execQuery(query, "/_search/scroll");
//		try {
//			if (respJson != null) {
//				JsonNode hits = respJson.get("hits").get("hits");
//				List<JsonNode> list = JsonUtils.toList(JsonUtils.toJson(hits), JsonNode.class);
//				if (!list.isEmpty()) {
//					data.put(SCORLL_ID, respJson.get("_scroll_id").asText());
//					data.put(HITS, list);
//				}
//			}
//		} catch (IOException e) {
//			log.error(e.getMessage(), e);
//		}
//		return data;
//	}
//}

}
